﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AdaptiveDeNet.DifferentialEvolution.Common
{
    public static class Common
    {
        public static double Zrdcad(double newVal, double lowerBound, double upperBound)
        {
            while (newVal < lowerBound || newVal > upperBound)
            {
                if (newVal < lowerBound)
                {
                    newVal = 2 * lowerBound - newVal;
                }
                else
                {
                    if (newVal > upperBound) newVal = 2 * upperBound - newVal;
                }
            }

            return newVal;
        }

        public static double FindMax(Member[] mainPop)
        {
            double ret = double.MinValue;

            for (int i = 0; i < mainPop.Length; i++)
            {
                if (ret < mainPop[i].FEval)
                {
                    ret = mainPop[i].FEval;
                }

            }

            return ret;
        }

        public static double[] GetBestMember(Member[] mainPop)
        {
            double helper = double.MaxValue;
            int bestMemberIndex = 0;

            for (int i = 0; i < mainPop.Length; i++)
            {
                if (helper > mainPop[i].FEval)
                {
                    helper = mainPop[i].FEval;
                    bestMemberIndex = i;
                }

            }

            double[] point = new double[mainPop[0].Vector.Length];

            Buffer.BlockCopy(mainPop[bestMemberIndex].Vector, 0, point, 0,
                mainPop[bestMemberIndex].Vector.Length * sizeof(double));

            return point;
        }

        internal static double[] GetBestMember(double[] mainPopHolder, int[] fitnessPointers, int N, int dim)
        {
            double helper = double.MaxValue;
            int bestMemberIndex = 0;

            for (int i = 0; i < N; i++)
            {
                if (helper > mainPopHolder[fitnessPointers[i]])
                {
                    helper = mainPopHolder[fitnessPointers[i]];
                    bestMemberIndex = i;
                }

            }

            double[] point = new double[dim];

            for (int i = 0; i < dim; i++)
            {
                point[i] = mainPopHolder[(fitnessPointers[i] - dim) + i];
            }

            return point;
        }
    }
}
